
import  Vue from 'vue'
import  VueRouter from  'vue-router'
import indexpage from  "../page/indexpage"
import  blog from  '../page/blog'
import  aboutMe from  '../page/aboutMe'
import  msgBroad from  '../page/msgBroad'
import  articleDetail from  '../page/articleDetail'
import  writeArticle from "../page/writeArticle"
import login from '../page/login'
import officeHelper from  '../page/office'
import axios from 'axios'

Vue.use(VueRouter)



let  router=new VueRouter({
     routes:[{
        path:"/index",
       component:indexpage
     },
       {
         path:"/",
         redirect:"/blog"   //修改 首页

       },{
        path:'/blog',
        component: blog,
      },{
         path:'/aboutMe',
         component:aboutMe
       },{
         path:'/msgBroad',
         component:msgBroad
       },
       {
         path:'/detail/:id',
         component:articleDetail
       },
       {
         path:'/write/:id',
         component:writeArticle,
         meta:{requireAuth:true}
       },
       {
         path:'/login',
         component: login
       },
       {
         path:'/officeHelper',
         component: officeHelper
       }


     ]
})

//全局的前置守卫， 可以用来判断是  需要登录的不使其 路由成功。
router.beforeEach((to,from,next) => {
   console.log("执行了路由判断")

   if(to.matched.some( (item) =>{
      return   item.meta.requireAuth ==true
   })){
     // 根据元信息来判断是否需要登录。
     axios.post("/validateLogin").then(success =>{

        if (success.data.code == 0) {
           next();
        }else {
          if(to.params.id){
            console.log(typeof (to.params.id))
             //虽然传递的是0,但是字符串类型的"0",所以为true.
            // this.$router.push({path:'/login',query:{id: to.params.id}})
            next({
              path: '/login?id='+to.params.id
            })

          }else {
            // this.$router.push({path:"/login"})
            next({
              path: '/login'
            })
          }
        }
      }).catch( error =>{
        // next({
        //   path: '/login'
        // })
      })

   }else {
      next()
   }

})

// const originalPush = VueRouter.prototype.push;
// VueRouter.prototype.push = function push(location, onResolve, onReject) {
//   if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
//   return originalPush.call(this, location).catch(err => err)
// }

export   default  router;
